<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="教学楼" prop="floorId">
        <el-select
          v-model="queryParams.floorId"
          placeholder="请选择教学楼"
          clearable
        >
          <el-option
            v-for="dict in dict.type.teaching_building"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="预约开始" prop="startDate">
        <el-date-picker
          clearable
          v-model="queryParams.startDate"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择预约开始"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item label="预约结束" prop="endDate">
        <el-date-picker
          clearable
          v-model="queryParams.endDate"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择预约结束"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:room:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:room:remove']"
          >删除</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:room:export']"
          >导出</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="roomList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="教室名称" align="center" prop="roomName" />
      <el-table-column label="教学楼" align="center" prop="floorId">
        <template slot-scope="scope">
          <dict-tag
            :options="dict.type.teaching_building"
            :value="scope.row.floorId"
          />
        </template>
      </el-table-column>
      <el-table-column
        label="教室图片"
        align="center"
        prop="roomImg"
        width="100"
      >
        <template slot-scope="scope">
          <image-preview :src="scope.row.roomImg" :width="50" :height="50" />
        </template>
      </el-table-column>
      <!-- <el-table-column label="富文本" align="center" prop="richText" /> -->
      <el-table-column label="排数" align="center" prop="rowNum" />
      <el-table-column label="列数" align="center" prop="columnNum" />
      <el-table-column
        label="座位json"
        align="center"
        prop="coordinateJson"
        v-if="false"
      />
      <el-table-column
        label="预约开始"
        align="center"
        prop="startDate"
        width="180"
      >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.startDate, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="预约结束"
        align="center"
        prop="endDate"
        width="180"
      >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.endDate, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column
        label="操作"
        align="center"
        width="160"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleRoom(scope.row)"
            v-hasPermi="['system:room:edit']"
            >配置</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:room:edit']"
            >修改</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:room:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 配置自习室对话框 -->
    <el-dialog
      :title="title"
      :visible.sync="openRoom"
      width="1000px"
      append-to-body
      :close-on-click-modal="false"
      @close="cancelRoom"
    >
      <el-form ref="form" :model="form" label-width="100px">
        <el-row
          type="flex"
          class="row-bg"
          justify="space-around"
          style="margin-bottom: 30px"
        >
          <el-col 
            ><div class="grid-content bg-purple">绿色为可预约</div></el-col
          >
          <el-col 
            ><div class="grid-content bg-purple-light">
              红色为已预约
            </div></el-col
          >
          <el-col 
            ><div class="grid-content bg-purple">
              灰色为系统配置不可预约（管理员可以点击那些不可预约，保存）
            </div></el-col
          >
        </el-row>

        <div style="overflow: scroll">
          <el-row
            type="flex"
            class="row-bg"
            v-for="(rows, index) in seatStatus"
            :key="index"
          >
            <el-col
              v-for="(cols, i) in rows"
              :key="i"
              style="line-height: 30px; cursor: pointer"
            >
              <div
                @click="handleSeatClick(cols)"
                class="grid-content bg-purple"
                style="background-color: gray; margin: 5px; width: 100px"
                v-if="cols.status === 2"
              >
                不可预约
              </div>
              <div
                @click="handleSeatClick(cols)"
                class="grid-content bg-purple"
                style="background-color: red; margin: 5px; width: 100px; color: #fff;"
                v-if="cols.status === 1"
              >
                已预约
              </div>
              <div
                @click="handleSeatClick(cols)"
                class="grid-content bg-purple"
                style="color: beige;background-color: green; margin: 5px; width: 100px"
                v-if="cols.status === 0"
              >
                可预约
              </div>
            </el-col>
          </el-row>
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handleSaveClick">确 定</el-button>
        <el-button @click="cancelRoom">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 添加或修改自习室对话框 -->
    <el-dialog
      :title="title"
      :visible.sync="open"
      width="500px"
      append-to-body
      @close="cancel"
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="教学楼" prop="floorId">
          <el-select v-model="form.floorId" placeholder="请选择教学楼">
            <el-option
              v-for="dict in dict.type.teaching_building"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="教室名称" prop="roomName">
          <el-input v-model="form.roomName" placeholder="请输入教室名称" />
        </el-form-item>

        <el-form-item label="教室图片" prop="roomImg">
          <image-upload v-model="form.roomImg" />
        </el-form-item>
        <el-form-item label="富文本">
          <editor v-model="form.richText" :min-height="192" />
        </el-form-item>
        <el-form-item label="排数" prop="rowNum">
          <el-input
            v-model="form.rowNum"
            placeholder="请输入排数"
            :disabled="disabledForm"
          />
        </el-form-item>
        <el-form-item label="列数" prop="columnNum">
          <el-input
            v-model="form.columnNum"
            placeholder="请输入列数"
            :disabled="disabledForm"
          />
        </el-form-item>
        <el-form-item v-if="false" label="座位json" prop="coordinateJson">
          <el-input
            v-model="form.coordinateJson"
            placeholder="请输入座位json"
          />
        </el-form-item>
        <el-form-item label="预约开始" prop="startDate">
          <el-date-picker
            clearable
            v-model="form.startDate"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择预约开始"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="预约结束" prop="endDate">
          <el-date-picker
            clearable
            v-model="form.endDate"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择预约结束"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="form.remark"
            type="textarea"
            placeholder="请输入内容"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listRoom,
  getRoom,
  delRoom,
  addRoom,
  updateRoom,
  submitRoomInfoForm,
} from "@/api/system/room";

export default {
  name: "Room",
  dicts: ["teaching_building"],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 自习室表格数据
      roomList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否显示自习室弹出层
      openRoom: false,
      seatStatus: [],
      numRows: 5,
      numCols: 8,
      disableSeatInput: "",
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        floorId: null,
        startDate: null,
        endDate: null,
      },
      // 表单参数
      form: {},
      //disabledForm 表单
      disabledForm: false,
      // 表单校验
      rules: {
        floorId: [
          { required: true, message: "教学楼不能为空", trigger: "change" },
        ],
        rowNum: [
          { required: true, message: "教室排数不能为空", trigger: "blur" },
        ],
        roomName: [
          { required: true, message: "教室名称不能为空", trigger: "blur" },
        ],
        columnNum: [
          { required: true, message: "教室列数不能为空", trigger: "blur" },
        ],
        startDate: [
          {
            required: true,
            message: "预约开始时间不能为空",
            trigger: "blur",
          },
        ],
        endDate: [
          {
            required: true,
            message: "预约结束时间不能为空",
            trigger: "blur",
          },
        ],
      },
    };
  },
  created() {
    this.getList();
  },
  methods: {
    // 处理座位点击事件
    handleSeatClick(data) {
      if (data.status === 1) {
        this.$modal.msgWarning("当前操作违法,因为已经有人预约了！");
        return;
      }

      let newData = this.seatStatus;

      if (data.status === 0) {
        newData[data.row][data.col] = {
          ...data,
          status: 2,
        };
        this.seatStatus = [...newData];
      }

      if (data.status === 2) {
        newData[data.row][data.col] = {
          ...data,
          status: 0,
        };
        this.seatStatus = [...newData];
      }
    },

    // 处理设置不可选座位按钮点击事件
    handleDisableSeatClick() {
      const seatToDisable = this.disableSeatInput;
      if (this.seatStatus[seatToDisable]) {
        this.$set(this.seatStatus, seatToDisable, "available");
      }
    },

    // 处理保存按钮点击事件
    handleSaveClick() {
      const seatStatusJson = JSON.stringify(this.seatStatus);

      // 在这里你可以将 seatStatusJson 发送到服务器保存，或者保存到本地存储中
      submitRoomInfoForm({
        coordinateJson: seatStatusJson,
        roomId: this.form.roomId,
      }).then((response) => {
        this.$modal.msgSuccess("修改成功");
        this.openRoom = false;
        this.reset();
      });
      // -----
    },

    /** 查询自习室列表 */
    getList() {
      this.loading = true;
      listRoom(this.queryParams).then((response) => {
        this.roomList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.disabledForm = false;
      this.open = false;
      this.reset();
    },
    // 取消配置自习室按钮
    cancelRoom() {
      this.openRoom = false;
      this.reset();
    },

    // 表单重置
    reset() {
      this.form = {
        roomId: null,
        floorId: null,
        roomImg: null,
        richText: null,
        rowNum: null,
        columnNum: null,
        coordinateJson: null,
        startDate: null,
        endDate: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null,
        roomName: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.roomId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加自习室";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const roomId = row.roomId || this.ids;
      getRoom(roomId).then((response) => {
        this.form = response.data;
        this.open = true;
        this.disabledForm = true;
        this.title = "修改自习室";
      });
    },
    /** 配置自习室操作 */
    handleRoom(row) {
      this.reset();
      const roomId = row.roomId;
      getRoom(roomId).then((response) => {
        let newForm = {
          ...response.data,
        };

        this.form = newForm;
        this.openRoom = true;
        this.seatStatus = JSON.parse(newForm.coordinateJson);

        this.title = "配置自习室座位";
      });
    },

    //处理座位状态
    seatStatusHandle(statu) {
      // 可选状态
      if (statu === 0) {
        return;
      } else if (statu === 1) {
        // 已选状态

        return;
      } else {
        // 限制不可选

        return;
      }
    },

    // 生成初始化座位表数组
    getInitMatrix({ rowNum, columnNum }) {
      let matrix = [];
      for (let i = 0; i < rowNum; i++) {
        matrix[i] = [];
        for (let j = 0; j < columnNum; j++) {
          matrix[i][j] = {
            row: i,
            col: j,
            status: 0,
          };
        }
      }

      return JSON.stringify(matrix);
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (!valid) {
          this.$modal.msgWarning("请按照要求提交！");
          return;
        }

        let newForm = {};

        newForm = {
          ...this.form,
        };

        if (this.form.roomId) {
          delete newForm.rowNum;
          delete newForm.columnNum;
          delete newForm.coordinateJson;
          debugger;
          updateRoom(newForm).then((response) => {
            this.$modal.msgSuccess("修改成功");
            this.open = false;
            this.disabledForm = false;
            this.getList();
          });
        } else {
          const { rowNum, columnNum } = newForm;

          newForm = {
            ...newForm,
            coordinateJson: this.getInitMatrix({ rowNum, columnNum }),
          };

          addRoom(newForm).then((response) => {
            this.$modal.msgSuccess("新增成功");
            this.open = false;
            this.getList();
          });
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const roomIds = row.roomId || this.ids;
      this.$modal
        .confirm('是否确认删除自习室编号为"' + roomIds + '"的数据项？')
        .then(function () {
          return delRoom(roomIds);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "system/room/export",
        {
          ...this.queryParams,
        },
        `room_${new Date().getTime()}.xlsx`
      );
    },
  },
};
</script>
<style>
.row-bg {
  text-align: center;
  padding: 10px 0;
  background-color: #f9fafc;
}
</style>

